<?php
namespace app\admin\controller;

use app\common\model\Software as M_Software;
use app\common\validate\Software as V_Software;
use bigDream\thinkJump\Jump;
use think\facade\Request;

/**
 * Class Software
 * @package app\admin\controller
 * @author jwj <jwjbjg@gmail.com>
 * @copyright jwj
 */
class Software
{
    /**
     * 软件列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        if (Request::isGet()) {
            return view();
        }

        $query = M_Software::autoSearch()
            ->with(['category'])
            ->append(['discard_text'])
            ->order('id', 'desc');

        $result = $query->paginate(Request::param('limit', 20));

        return json([
            'code'  => 0,
            'msg'   => '获取成功',
            'count' => $result->total(),
            'data'  => $result->items()
        ]);
    }

    /**
     * 添加软件
     * @return \think\response\View
     */
    public function add()
    {
        if (Request::isGet()) {
            return view('software/edit');
        }

        $validate = (new V_Software())->scene('add');
        $data = Request::only($validate->getSceneField());
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        M_Software::startTrans();
        try {
            $result = M_Software::create($data);

            M_Software::commit();
        } catch (\Exception $e) {
            M_Software::rollback();

            Jump::error('发生错误:' . $e->getMessage());
        }

        Jump::success('添加成功');
    }

    /**
     * 编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $result = M_Software::where('id', Request::param('id'))->find();
        if (null === $result) {
            Jump::error('内容不存在');
        }

        if (!Request::isAjax()) {
            return view('', [
                'result' => $result,
            ]);
        }

        $validate = (new V_Software())->scene('edit');
        $data = Request::only($validate->getSceneField());
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        M_Software::startTrans();
        try {
            $result->save($data);

            M_Software::commit();
        } catch (\Exception $e) {
            M_Software::rollback();

            Jump::error('发生错误:' . $e->getMessage());
        }

        Jump::success('修改成功');
    }

    /**
     * 编辑字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editColumn()
    {
        $data = Request::only(['id', 'name', 'value']);
        if (!isset($data['name']) || !isset($data['value'])) {
            Jump::error('缺少参数');
        }

        $allowField = ['latest'];
        if (!in_array($data['name'], $allowField)) {
            Jump::error('该字段不允许编辑');
        }

        $validate = (new V_Software())->only(['id', $data['name']]);
        $data = ['id' => $data['id'], $data['name'] => $data['value']];
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        $result = M_Software::where('id', $data['id'])->find();
        if (null === $result) {
            Jump::error('内容不存在');
        }

        try {
            $result->save($data);
        } catch (\Exception $e) {
            Jump::error('发生错误:' . $e->getMessage());
        }

        Jump::success('编辑成功');
    }

    /**
     * 删除软件
     */
    public function delete()
    {
        M_Software::startTrans();
        try {
            $result = M_Software::where('id', 'in', Request::param('id'))->select();

            foreach ($result as $res) {
                $path = app()->getRootPath() . 'public/' . $res['url'];
                if (file_exists($path) && is_file($path)) unlink($path);

                $res->delete();
            }

            M_Software::commit();
        } catch (\Exception $e) {
            M_Software::rollback();

            Jump::error($e->getMessage());
        }

        Jump::success('删除成功');
    }

    /**
     * 废弃软件
     */
    public function discard()
    {
        M_Software::startTrans();
        try {
            $result = M_Software::where('id', 'in', Request::param('id'))->select();

            foreach ($result as $res) {
                $path = app()->getRootPath() . 'public/' . $res['url'];
                if (file_exists($path) && is_file($path)) unlink($path);

                $res->save(['discard' => 1]);
            }

            M_Software::commit();
        } catch (\Exception $e) {
            M_Software::rollback();

            Jump::error($e->getMessage());
        }

        Jump::success('废弃成功');
    }
}